package com.knowswift.security.handler.success;

import com.knowswift.common.bean.issue.po.IssueNew;
import com.knowswift.common.utils.JwtTokenUtils;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import com.knowswift.security.account.UserVO;
import com.knowswift.security.handler.AbstractLoginSuccessHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @company https://www.knowswift.com
 */
@Component
public class AdminPasswordLoginSuccessHandler extends AbstractLoginSuccessHandler {
    @Resource
    private UserService userService;

    @Override
    public Object preAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        User user = (User) authentication.getPrincipal();
//        if (!user.getRole().equals(PropertyConfig.ROLE_USER)) {
//            sendResponse(httpServletResponse, Result.NO_ACCESS, "无权访问", null);
//            return null;
//        }
        user.setAdminTokenVersion(user.getAdminTokenVersion() + 1);
        userService.updateById(user);
        Map<String, Object> claims = new HashMap<>();
        claims.put("tokenVersion", user.getAdminTokenVersion());
        String token = JwtTokenUtils.generateToken(claims, user.getId());

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        //UserVO userVO = WrappedBeanCopier.copyProperties(user, UserVO.class);
        userVO.setToken(token);
        return userVO;
    }
}
